<?php
declare(strict_types=1);

namespace Modules\Base\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Modules\Base\Http\Requests\BoxRequest;
use Modules\Base\Repository\BoxNumberRepository;use Modules\Base\Service\BoxService;use Modules\Base\Service\TaskScanService;
use App\Enums\BoxFrom;
use Modules\Base\Models\BoxNumber;

class BoxController extends Controller
{
    public function __construct(
        protected readonly BoxNumber $model
    ){}

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(): mixed
    {
        $list = $this->model->getList()->toArray();
        foreach ($list['data'] as &$val){

            if(empty($val['img'])){
                $val['img'] = trim(env('APP_URL'),'/') . '/api/qrcode/' . $val['code'];
            }else{
                $val['img'] = trim(env('APP_URL'),'/') . $val['img'];
            }

        }
        return $list;
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(BoxRequest $request)
    {

        $size       = $request->post('count',0);
        $boxType    = $request->post('box_type',1);
        if($size <= 0){
            throw new \Exception('生成数量必须大于0');
        }

        return BoxService::makeBoxNumber($size,BoxFrom::MANUAL_CREATION->value,0,'','','',false,$boxType);

    }

    /**
     * @param $idl
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, BoxRequest $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return $this->model->deleteBy($id);
    }

    /**
     * enable
     *
     * @param $id
     * @return bool
     */
    public function enable($id)
    {
        return $this->model->toggleBy($id,'active');
    }

    /**
     * 箱号操作日志
     * @param $lotnum
     * @return array
     */
    public function log($lotnum){
        return BoxNumberRepository::getBoxLog($lotnum);
    }

    /**
     * 检查箱号是否存在
     * @param $lotnum
     * @return mixed
     * @throws Exception
     */
    public function existLotnum($lotnum){
        $box = BoxNumberRepository::getBoxByCode($lotnum);
        if(!$box){
            throw new \Exception('箱号不存在');
        }
        return $box;
    }


}
